ALTER PROCEDURE [dbo].[wp_List_Generic]
  @Table VARCHAR(4000),
 @DefaultSort VARCHAR(4000),

 @Start INT = 0,  
 @Limit INT = 25,  
 @Order VARCHAR(4000) = 'descripcion',  
 @Direction VARCHAR(4) = 'ASC',  
   
 @Filtro VARCHAR(4000) = NULL  
AS 
 DECLARE @SQL NVARCHAR(4000),  
	@ParmDefinition NVARCHAR(4000) 
 SET @Order = ISNULL(@Order, @DefaultSort)
 SET @ParmDefinition = N'@Start INT, @Limit INT'  
 IF(@Limit > 0)
 BEGIN
	 SET @SQL = N'
		SELECT * FROM
		(
		SELECT TOP ' + Cast( @limit as varchar) + N' * FROM 
				(
				SELECT TOP ' + Cast( @start+@limit as varchar) + N'
					 *
					 From '+@Table
					 
					IF(NOT @Filtro IS NULL AND @Filtro <> '')  
					BEGIN   
					 SET @SQL = @SQL + ' Where ' + @Filtro  
					END
					
					 SET @SQL = @SQL + ' order by ' + @Order + ' ASC
				)  as Result   
				Order by ' + @Order + ' DESC
		 )  as Result '
		
		SET @SQL = @SQL + N' ORDER BY '+ @Order+ ' ASC' 
 END
 ELSE
 BEGIN
	SET @SQL = N'
		SELECT *
		FROM '+@Table
				
	IF(NOT @Filtro IS NULL AND @Filtro <> '')  
	BEGIN   
	 SET @SQL = @SQL + ' Where ' + @Filtro  
	END 
	
	SET @SQL = @SQL + N' ORDER BY '+ @Order+ ' ASC' 
 END	
     
SET @SQL = @SQL + '  
	Select Count(1)  
	From ' + @Table
	
	IF(NOT @Filtro IS NULL AND @Filtro <> '')  
	BEGIN   
	 SET @SQL = @SQL + ' Where ' + @Filtro  
	END 
	--PRINT @SQL
EXECUTE sp_executesql @SQL  
